//引入express模块
const express = require('express');
//引入连接池模块
const pool = require('../pool.js');
//console.log(pool);
//创建路由器对象
const router = express.Router();


//用户注册
router.post('/register',(req,res)=>{
	var phone= req.body.phone;
  var obj=req.body
	var sql = 'select * from se_user where phone=?';
  pool.query(sql,[phone],(error, result) => {
		if(error) throw error;
		console.log(result.length)
		if(result.length==0){
  var sql="insert into se_user set ?";
  pool.query(sql,[obj],(error,result)=>{
		   if(error) throw error;
        res.send({ message: '注册成功！', code: 200 });
      })
    } else {
      res.send({ message: '注册失败！', code: 201 });
    }
  });
});


//用户登录
router.post('/login',(req,res)=>{
  var phone=req.body.phone;
  var spwd=req.body.spwd;
  console.log(phone,spwd);
  var sql="select * from se_user where phone=? and spwd=?";
  pool.query(sql,[phone,spwd],(error,result)=>{
	if(error) throw error;
	console.log(result)
	if(result.length===0){
		res.send({code:-1,msg:"用户名或者密码错误"});
	}else{
		res.send({code:1,msg:"登录成功",result});
	}
  })
})

//修改用户(put revise)
//http://127.0.0.1:8080/v1/users/revise
router.put('/revise',(req,res)=>{
  //3.1获取post传递的数据(uid、email、phone、user_name、gender)
  let obj = req.body;
  //3.3执行SQL命令，修改用户的数据
pool.query('update se_user set ? where phone=?',[obj,obj.phone],(error,result)=>{
    if(error) throw error;
  	console.log(result)
  	//结果是对象，如果对象下的affectedRows的值是0说明修改失败，否则修改成功
  	if(result.affectedRows === 0){
  	  res.send({code: 201,msg: '修改失败'});
  	}else{
  	  res.send({code: 200, msg: '修改成功'});
  	}
  });
});
//导出路由器对象
module.exports = router;